use crate::cli::csv::OutputFormat;
use csv::Reader;
use serde_json::Value;
use std::{fmt, fs};

pub fn process_into_csv(input: &str, output: String, format: OutputFormat) -> anyhow::Result<()> {
    let mut reader = Reader::from_path(input)?;
    let mut ret = Vec::new();
    let headers = reader.headers()?.clone();
    for result in reader.records() {
        let record = result?;
        let json_value: Value = headers.iter().zip(record.iter()).collect::<Value>();
        ret.push(json_value);
    }
    // let json = serde_json::to_string_pretty(&ret)?;
    let content: String = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&ret)?,
        OutputFormat::Yaml => serde_yaml::to_string(&ret)?,
    };
    fs::write(output, content)?;
    Ok(())
}

impl fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OutputFormat::Json => write!(f, "json"),
            OutputFormat::Yaml => write!(f, "yaml"),
        }
    }
}
